import { Table, Space, Button, Tag, Drawer, Tree, Form, Input, Select, message, Popconfirm } from 'antd'
import { useState, useEffect, useCallback } from 'react'
import { addAdmin, getAdminList, deleteAdmin } from './../../api/admin'
import menus from '../../router/menus'
const Com = () => {
  // 请求列表数据
  const [adminList, setAdminList] = useState([])
  useEffect(() => {
    getAdminList().then(res => {
      setAdminList(res.data)
    })
  })

  const columns = [
    {
      title: '序号',
      render (text, record, index) { // render: (text, record, index) => {} ， 箭头函数默认返回出来，多条语句return 出来
        return (
          <span>{ (current-1)*pageSize + index + 1 }</span>
        )
      }
    },
    {
      title: '账号',
      dataIndex: 'adminname'
    },
    {
      title: '权限',
      dataIndex: 'role',
      render (text) {
        return (
          <>
            {
              text === 2 ? <Tag color="green">超级管理员</Tag> : <Tag color="#55acee">管理员</Tag>
            }
          </>
        )
      }
    },
    {
      title: '操作',
      render (text, record, index) {
        // console.log(record);
        // console.log('1', text);
        return (
          <Space>
            <Button type="ghost">编辑</Button>
            <Popconfirm
              title="确认删除?"
              onConfirm={ () => {
                deleteAdmin({ adminid: record.adminid }).then(res => {
                  getAdminList().then(res => {
                    setAdminList(res.data)
                  })
                })
                console.log('删除成功')
              }}
              onCancel={() => {}}
              okText="确定"
              cancelText="取消"
            >
            <Button danger >删除</Button>
              {/* <Button danger onClick = {() => {
                deleteAdmin({ adminid: record.adminid }).then(res => {
                  setAdminList(res.data)
                })
                getAdminList().then(res => {
                  setAdminList(res.data)
                })
              }}>删除</Button> */}
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  // 分页器
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  // 添加管理员
  const [addVisible, setAddVisible] = useState(false); // 管理员抽屉
  const [adminname, setAdminname] = useState('');
  const [password, setPassword] = useState('');
  const [role, setRole] = useState(1);
  const [checkedKeys, setCheckedKeys] = useState(['0-0']); // （受控）设置选中的树节点

  const onAddOpen = useCallback(() => {
    setAddVisible(true)
  }, [])

  const onAddClose = useCallback(() => {
    setAddVisible(false)
  }, [])

  const onCheck = useCallback((checkedKeys) => {
    setCheckedKeys(checkedKeys)
  }, [])

//   const add = {
//     adminname: '11',
//     password: 222,
//     role: 2,
//     checkedKeys: ['0-0','0-1']
//   }
// setInterval(() => {
//   getAdminList().then(res => {
//     if(res.data[0].adminname !== "11") {
//       addAdmin(add).then(res => {
//         // console.log(res);
//       })
//     } else {
//       // console.log('已存在');
//     }
//   })
// }, 1000);

  const addAdminFn = useCallback(() => {
    const data = {
      adminname,
      password,
      role,
      checkedKeys // 打开的权限
    }
    console.log(data)
    addAdmin(data).then(res =>{
      if (res.code === '10004') {
        message.error('该管理员已存在')
      } else {
        // 清空表单的数据，方便下次添加，其次让抽屉消失，然后重新请求数据
        setAdminname('')
        setPassword('')
        setRole(1)
        setCheckedKeys(['0-0'])

        setAddVisible(false)

        getAdminList().then(res => {
          setAdminList(res.data)
          console.log('11', res.data);
        })
      }
    })
  }, [adminname, password, role, checkedKeys])

  return (
    <Space direction = "vertical" style={{ width: '100%', height: '100%', overflow:'auto'}}>
      <Button type = "primary" onClick = { onAddOpen }>添加管理员</Button>
      <Table
        dataSource = { adminList } 
        columns = {columns} 
        rowKey = "adminid"
        pagination = { {
          position: ['bottomRight'],
          current, // 当前页数
          pageSize, // 每页条数
          onChange: (page, pageSize) => { // 页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
            setCurrent (page)
            setPageSize(pageSize)
          },
          pageSizeOptions: ['5', '10', '15', '20'], // 指定每页可以显示多少条 // 看不加引号会不会报错
          showQuickJumper: true, // 是否可以快速跳转至某页
          showTotal: (total) => <span>共有{total}条数据</span>
        } }
      />
      {/* 添加管理员抽屉 */}
      <Drawer 
        title="管理员"
        placement="right"
        width = "500"
        onClose={onAddClose}
        visible={addVisible}
      >
        <Form
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 14,
            }}
            layout="horizontal"
          >
            <Form.Item label="账户">
              <Input placeholder="管理员账户" value = {adminname} onChange = {e => setAdminname(e.target.value)} />
            </Form.Item>
            <Form.Item label="密码">
              <Input placeholder="密码" value = {password} onChange = {e => setPassword(e.target.value)} />
            </Form.Item>
            <Form.Item label="权限">
              <Select defaultValue = { 1 } value = { role } onChange = {value => setRole(value)}>
                <Select.Option value = { 1 } >管理员</Select.Option>
                <Select.Option value = { 2 } >超级管理员</Select.Option>
              </Select>
            </Form.Item>
            {/* 树形控件 */}
            <Form.Item>
              <Tree
                checkable
                onCheck={onCheck} // 	点击复选框触发
                checkedKeys={checkedKeys}
                treeData={menus}
              />
            </Form.Item>
            <Form.Item 
              labelCol = {{
                offset: 4,
                span: 4
              }}
              >
              <Button type="primary" onClick = { addAdminFn }>添加管理员</Button>
            </Form.Item>
        </Form>
      </Drawer>
    </Space>
  )
}

export default Com